package com.jeesit.cloud.spot.web.interceptor;

import com.alibaba.fastjson.JSON;
import com.jeesit.cloud.annotation.ModuleLog;
import com.jeesit.cloud.constants.LogConstant;
import com.jeesit.cloud.constants.LoginConstants;
import com.jeesit.cloud.dto.LogInfo;
import com.jeesit.cloud.dto.UserLogDto;
import com.jeesit.cloud.feign.IUserFeign;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

/**
 * @author syd
 * @date 2023/05/04
 */
@Slf4j
@Component
public class ModuleInteceptor implements HandlerInterceptor {
    @Autowired
    private IUserFeign userFeign;

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
        String realIp = request.getHeader(LogConstant.REAL_IP);
        if (handler instanceof HandlerMethod) {
            try {
                String moduleCode = request.getParameter(LogConstant.MODULE_CODE);
                ModuleLog moduleLog = ((HandlerMethod) handler).getMethod().getAnnotation(ModuleLog.class);
                if (moduleLog != null) {
                    String[] module = moduleLog.value();
                    int type = moduleLog.type();
                    if (module != null) {
                        LogInfo logInfo = (LogInfo) request.getAttribute(LogConstant.LOG_KEY);
                        if (logInfo != null) {
                            Map<String, String[]> parameterMap = request.getParameterMap();
                            // 后台用户
                            if (type == LoginConstants.USER_TYPE_2) {
                                UserLogDto userLog = new UserLogDto();
                                userLog.setUserId(logInfo.getOperateId());
                                userLog.setOptTime(new Date());
                                userLog.setIp(realIp);
                                userLog.setModuleCode(module[0]);
                                if (StringUtils.isNotBlank(moduleCode)) {
                                    for (String code : module) {
                                        if (StringUtils.indexOf(code, moduleCode) > -1) {
                                            userLog.setModuleCode(moduleCode);
                                        }
                                    }
                                }
                                userLog.setOptContent(logInfo.getOptContent());
                                userLog.setReqParams(JSON.toJSONString(parameterMap));
                                userFeign.saveUserLog(userLog);
                            }
                        //    if (type == LoginConstants.USER_TYPE_1) {
                        //        // 前台用户机构日志
                        //        CompanyLogDto companyLog = new CompanyLogDto();
                        //        companyLog.setCompanyId(logInfo.getOperateId());
                        //        companyLog.setOptTime(new Date());
                        //        companyLog.setIp(realIp);
                        //        companyLog.setContent(logInfo.getOptContent());
                        //        companyLog.setReqParams(JSON.toJSONString(parameterMap));
                        //        userFeign.saveCompanyLog(companyLog);
                        //    }
                        }
                    }
                }
            } catch (Exception e) {
                log.warn(e.getMessage(), e);
            }
        }
    }

    /**
     * 获取客户端真实Ip
     *
     * @param request
     * @return
     */
    private String getClientIp(HttpServletRequest request) {
        String fromSource = "X-Real-IP";
        final String unknown = "unknown";
        final String xRealIp = "X-Real-IP";
        final String xForwardedFor = "X-Forwarded-For";
        final String proxyClientIp = "Proxy-Client-IP";
        final String wlProxyClientIp = "WL-Proxy-Client-IP";

        String ip = request.getHeader(xRealIp) == null ? request.getHeader("remote-ip") : request.getHeader(xRealIp);
        if (ip == null || ip.length() == 0 || unknown.equalsIgnoreCase(ip)) {
            ip = request.getHeader(xForwardedFor);
            fromSource = xForwardedFor;
        }
        if (ip == null || ip.length() == 0 || unknown.equalsIgnoreCase(ip)) {
            ip = request.getHeader(proxyClientIp);
            fromSource = proxyClientIp;
        }
        if (ip == null || ip.length() == 0 || unknown.equalsIgnoreCase(ip)) {
            ip = request.getHeader(wlProxyClientIp);
            fromSource = wlProxyClientIp;
        }
        if (ip == null || ip.length() == 0 || unknown.equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
            fromSource = "request.getRemoteAddr";
        }
        log.info("App Client IP: {}, fromSource: {}", ip, fromSource);
        return ip;
    }
}
